import { reactive } from 'vue'
import { defineStore,skipHydrate } from 'pinia'
import type { UserInfo } from '@/type/all-type'
import { useLocalStorage } from '@vueuse/core'

export const userInfoState = defineStore('userStates', () => {


  const user: UserInfo = reactive({})
  const userStates = useLocalStorage("user", user)

  /**
   * 设置用户登陆状态
   * @param usr 
   */
  function setUser(usr: UserInfo) {
    if (usr.userName) {
      userStates.value.userName = usr.userName
    }
    if (usr.userId) {
      userStates.value.userId = usr.userId
    }
    if (usr.webSocketId) {
      userStates.value.webSocketId = usr.webSocketId
    }
    if (usr.privileges) {
      userStates.value.privileges = usr.privileges
    }
  }

  /**
   * 移除用户登陆状态
   */
  function removeUser() {
    delete userStates.value.userId
    delete userStates.value.userName
    delete userStates.value.webSocketId
    delete userStates.value.privileges
  }


  /**
   * 判断当前用户是否登陆
   * @returns 
   */
  function isLogin() {
    return userStates.value.userId != null
  }

  /**
   * 判断用户是否有该权限
   * @param privilege 
   */
  function hasPrivilege(privilege: string): boolean {
    return userStates.value.privileges!.includes(privilege);
  }


  return { user: skipHydrate(userStates), setUser, removeUser, isLogin, hasPrivilege }

})